package com.zyt.login.servlet;

import com.zyt.login.dao.UserDao;
import com.zyt.login.domain.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("Login Servlets");
        System.out.println("req = " + req);

//        String username = req.getParameter("username");
//        String password = req.getParameter("password");
//
//        User loginUser = new User();
//        loginUser.setUsername(username);
//        loginUser.setPassword(password);

        User loginUser = new User();
        try {
            // BeanUtils 用户封装JavaBean，符合以下要求
            // 类必须是Public
            // 提供空构造
            // 属性成员使用private修饰
            // 提供Getter/Setter方法
            BeanUtils.populate(loginUser, req.getParameterMap());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        UserDao dao = new UserDao();
        User user = dao.login(loginUser);

        if (user != null) {
            req.setAttribute("user", user);
            req.getRequestDispatcher("/successServlet").forward(req, resp);
        } else {
            req.getRequestDispatcher("/failedServlet").forward(req, resp);
        }
    }
}
